package com.qos.oauth;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.UnsupportedEncodingException;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLEncoder;
import java.util.Random;

import javax.crypto.Mac;
import javax.crypto.spec.SecretKeySpec;


import android.util.Log;

public class ApiHelper{
	public static final String TAG = "ApiHelper";
	
	public static int updata(String msg){
		HttpURLConnection con = null; 
		Random RAND = new Random();
		String consumerSecret=OAuthHelper.appSecret;
		String method="POST";
		String url="http://api.t.sina.com.cn/statuses/update.json";
		
		String oauth_consumer_key=OAuthHelper.appKey;
		long  oauth_nonce;
		String oauth_signature_method="HMAC-SHA1";
		long oauth_timestamp;
		String oauth_token=OAuthHelper.oauth_access_token;
		String oauth_version="1.0";
		String status=null;
		try {
			status = URLEncoder.encode(msg,"UTF-8");
		} catch (UnsupportedEncodingException e3) {
			// TODO Auto-generated catch block
			e3.printStackTrace();
		}		
			
		oauth_timestamp = System.currentTimeMillis() / 1000;
		oauth_nonce = oauth_timestamp + RAND.nextInt();

		String baseString="oauth_consumer_key="+
				oauth_consumer_key+"&oauth_nonce="+oauth_nonce+"&oauth_signature_method="+oauth_signature_method+
				"&oauth_timestamp="+oauth_timestamp+"&oauth_token="+oauth_token+"&oauth_version="+oauth_version+"&status="+status;
		String tempStr=null;
		try {
			baseString=URLEncoder.encode(baseString,"UTF-8");
			tempStr=URLEncoder.encode(url,"UTF-8");
		} catch (UnsupportedEncodingException e2) {
			// TODO Auto-generated catch block
			e2.printStackTrace();
		}
		baseString=method+'&'+tempStr+"&"+baseString;
		byte[] byteHMAC = null;
		String oauth_signature=null;
		
		Mac mac = null;
		try {
			mac = Mac.getInstance("HmacSHA1");
			String key = URLEncoder.encode(consumerSecret,"UTF-8") + "&"+URLEncoder.encode(OAuthHelper.oauth_access_token_secret,"UTF-8") ;
			SecretKeySpec spec = new SecretKeySpec(key.getBytes(), "HmacSHA1");
			mac.init(spec);
			byteHMAC = mac.doFinal(baseString.getBytes());
			oauth_signature = new BASE64Encoder().encode(byteHMAC);
			oauth_signature=URLEncoder.encode(oauth_signature,"UTF-8");
		} catch (Exception e1) {
			// TODO Auto-generated catch block
			oauth_signature="error";
			e1.printStackTrace();
		}	
			
	     String httpHeaderStr="OAuth oauth_consumer_key=\""+
	     oauth_consumer_key+"\",oauth_signature_method=\""+
	     		oauth_signature_method+"\",oauth_timestamp=\""+
	     oauth_timestamp+"\",oauth_nonce=\""+
	     		oauth_nonce+"\",oauth_version=\""+
	     oauth_version+"\",oauth_signature=\""+
	     		oauth_signature+"\",oauth_token=\""+
	     oauth_token+"\"";
			
	      try {
	    	URL postUrl = new URL(url);  
			con = (HttpURLConnection) postUrl.openConnection();
			con.setConnectTimeout(20000);
	        con.setReadTimeout(12000);
			con.addRequestProperty("Authorization", httpHeaderStr);
	        con.setRequestMethod("POST");
	        con.setDoOutput(true);
	        con.setDoInput(true);
	        status="status="+status;
	        byte[] bytes = status.getBytes("UTF-8");
			OutputStream osw = con.getOutputStream();
			osw.write(bytes);
			osw.flush();
			osw.close();
			int code = con.getResponseCode();
			if (code == 200) {
				InputStream is = con.getInputStream();
				BufferedReader br = new BufferedReader(new InputStreamReader(
						is, "UTF-8"));
				StringBuffer buf = new StringBuffer();
				String line;
	
				while (null != (line = br.readLine())) {
					buf.append(line).append("\n");
				}
				System.out.println(buf);
				return code;
			} else {
	
				return code;
			}
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			return 0;
		}
	}
	
	public static void getUserInfo(){
		HttpURLConnection con = null; 
		Random RAND = new Random();
		String consumerSecret=OAuthHelper.appSecret;
		String method="GET";
		String url="http://api.t.sina.com.cn/users/show.json";
		
		String oauth_consumer_key=OAuthHelper.appKey;
		long  oauth_nonce;
		String oauth_signature_method="HMAC-SHA1";
		long oauth_timestamp;
		String oauth_token=OAuthHelper.oauth_access_token;
		String oauth_version="1.0";
		String user_id=null;
		try {
			user_id = URLEncoder.encode(OAuthHelper.oauth_user_id,"UTF-8");
		} catch (UnsupportedEncodingException e3) {
			// TODO Auto-generated catch block
			Log.d(TAG, e3.toString());
		}		
		
		oauth_timestamp = System.currentTimeMillis() / 1000;
		oauth_nonce = oauth_timestamp + RAND.nextInt();

		String baseString="oauth_consumer_key="+
				oauth_consumer_key+"&oauth_nonce="+
				oauth_nonce+"&oauth_signature_method="+
				oauth_signature_method+"&oauth_timestamp="+
				oauth_timestamp+"&oauth_token="+
				oauth_token+"&oauth_version="+
				oauth_version+"&uid="+user_id;
		
		String tempStr=null;
		try {
			baseString=URLEncoder.encode(baseString,"UTF-8");
			tempStr=URLEncoder.encode(url,"UTF-8");
		} catch (UnsupportedEncodingException e2) {
			// TODO Auto-generated catch block
			Log.d(TAG, e2.toString());
		}
		baseString=method+'&'+tempStr+"&"+baseString;
		
		byte[] byteHMAC = null;
		String oauth_signature=null;				 
		Mac mac = null;
		try {
			mac = Mac.getInstance("HmacSHA1");
			String key = URLEncoder.encode(consumerSecret,"UTF-8") + "&" +
				URLEncoder.encode(OAuthHelper.oauth_access_token_secret,"UTF-8") ;
			SecretKeySpec spec = new SecretKeySpec(key.getBytes(), "HmacSHA1");
			mac.init(spec);
			byteHMAC = mac.doFinal(baseString.getBytes());
			oauth_signature = new BASE64Encoder().encode(byteHMAC);
			oauth_signature=URLEncoder.encode(oauth_signature,"UTF-8");
		} catch (Exception e1) {
			// TODO Auto-generated catch block
			oauth_signature="error";
			Log.d(TAG, e1.toString());
		}	
			
	     String httpHeaderStr="OAuth oauth_consumer_key=\""+
	     oauth_consumer_key+"\",oauth_signature_method=\""+
	     		oauth_signature_method+"\",oauth_timestamp=\""+
	     oauth_timestamp+"\",oauth_nonce=\""+
	     		oauth_nonce+"\",oauth_version=\""+
	     oauth_version+"\",oauth_signature=\""+
	     		oauth_signature+"\",oauth_token=\""+
	     oauth_token+"\"";
			
	     // 打开连接  
	     try {
	    	URL postUrl = new URL(url);  
			con = (HttpURLConnection) postUrl.openConnection();
			con.setConnectTimeout(20000);
	        con.setReadTimeout(12000);
			con.addRequestProperty("Authorization", httpHeaderStr);
            con.setRequestMethod("GET");
            con.setDoOutput(true);
            con.setDoInput(true);
            user_id="uid="+user_id;
            byte[] bytes = user_id.getBytes("UTF-8");
			OutputStream osw = con.getOutputStream();
			osw.write(bytes);
			osw.flush();
			osw.close();
			int code = con.getResponseCode();
			InputStream is = con.getInputStream();
			BufferedReader br = new BufferedReader(new InputStreamReader(
					is, "UTF-8"));
			StringBuffer buf = new StringBuffer();
			String line;

			while (null != (line = br.readLine())) {
				buf.append(line).append("\n");
			}
			Log.d(TAG, buf.toString());
		} catch (IOException e) {
			// TODO Auto-generated catch block
			Log.d(TAG, e.toString());
		}
	}
}
